package com.yami.shop.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author lhd
 * @date 2020-05-12 08:21:24
 */
@RestController
@RequestMapping("/p/myNotifyLog")
@Tag(name = "消息接口")
public class NotifyLogController {

    @Autowired
    private NotifyLogService notifyLogService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserBlockService userBlockService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private MeltCloudUserRemarkService userRemarkService;


    @GetMapping("/unReadCount")
    @Operation(summary =  "查询系统公告未读消息数量", description = "查询未读消息数量")
    public ServerResponseEntity<Long> getNotifyCount() {
        String userId = SecurityUtils.getUser().getUserId();
        return ServerResponseEntity.success(notifyLogService.countUnreadMsg(userId));
    }

    @GetMapping("/unReadCountList")
    @Operation(summary =  "查询消息列表", description = "查询消息列表")
    @Parameter(name = "status", description = "状态 0未读 1已读 -1删除,默认为0")
    public ServerResponseEntity<IPage<NotifyLog>> getUnReadCountList(PageParam<NotifyLog> page, Integer status) {
        String userId = SecurityUtils.getUser().getUserId();
        status = Objects.isNull(status) ? 0 : status;
        IPage<NotifyLog> notifyReminds = notifyLogService.page(page,
                new LambdaQueryWrapper<NotifyLog>()
                        .eq(NotifyLog::getRemindId, userId)
                        .ne(NotifyLog::getStatus, -1)
                        .lt(NotifyLog::getSendType, 51)
                        .eq(NotifyLog::getRemindType, 3)
                        .orderByAsc(NotifyLog::getStatus)
                        .orderByDesc(NotifyLog::getCreateTime));
        List<NotifyLog> records = notifyReminds.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            notifyLogService.readLog(userId);
        }
        return ServerResponseEntity.success(notifyReminds);
    }



    @GetMapping("/getCommentList")
    @Operation(summary =  "查询评论消息列表", description = "查询评论消息列表")
    public ServerResponseEntity<IPage<NotifyLog>> getCommentList(PageParam<NotifyLog> page) {
        String userId = SecurityUtils.getUser().getUserId();
        LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, userId);
        List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
        IPage<NotifyLog> notifyReminds = notifyLogService.page(page,
                new LambdaQueryWrapper<NotifyLog>()
                        .eq(NotifyLog::getRemindId, userId)
                        .ne(NotifyLog::getStatus, -1)
                        .eq(NotifyLog::getType,1)
                        .eq(NotifyLog::getRemindType, 3)
                        .notIn(CollUtil.isNotEmpty(blockUserIds), NotifyLog::getUserId, blockUserIds)
                        .orderByDesc(NotifyLog::getCreateTime));
        List<NotifyLog> records = notifyReminds.getRecords();
        List<String> userIds = new ArrayList<>();
        List<Long> blogs = new ArrayList<>();
        List<Long> comments = new ArrayList<>();
        records.forEach(record -> {
                record.setStatus(1);
                userIds.add(record.getUserId());
                if(record.getProdId()!=null){
                    comments.add(record.getProdId());
                }else{
                    blogs.add(Long.valueOf(record.getBlogId()));
                }
            });
        // 获取用户列表
        Collection<User> userList = new ArrayList<>();
        Map<String, String> remarkMap = new HashMap<>();
        if (userIds.size() > 0) {
            userList = userService.listByIds(userIds);
            List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, userIds));
            remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        }
        // 过滤掉用户的敏感信息
        List<User> filterUserList = new ArrayList<>();
        Map<String, String> finalRemarkMap = remarkMap;
        userList.forEach(item -> {
            User user = new User();
            user.setPic(item.getPic());
            user.setUserId(item.getUserId());
            String name = item.getNickName();
            if (StringUtils.isNotEmpty(finalRemarkMap.get(item.getUserId()))) {
                name = finalRemarkMap.get(item.getUserId());
            }
            user.setNickName(name);
            user.setIsHasRealName(StrUtil.isNotEmpty(item.getRealName()));
            filterUserList.add(user);
        });
        if(userIds.contains("admin")){
            User user = new User();
//            user.setPic(item.getPic());
            user.setUserId("admin");
            user.setNickName("平台");
            filterUserList.add(user);
        }
        List<User> filterUserListTo = filterUserList.stream().distinct().collect(Collectors.toList());
        Map<String, User> userMap = filterUserListTo.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
        Map<Long, Comment> commentMap = null;
        //获取评论或者博客内容
        if(comments.size()>0){
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            wrapper.in("uid",comments);
            //分页
            wrapper.eq("status", 1);
            // 查询出该文章下所有的子评论
            List<Comment> allCommentList = commentService.list(wrapper);
            commentMap = allCommentList.stream().collect(Collectors.toMap(Comment::getUid, Function.identity()));
        }
        Map<Long, Blog> blogMap= null;
        if(blogs.size()>0){
            LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            blogLambdaQueryWrapper.eq(Blog::getStatus,1);//审核通过
            blogLambdaQueryWrapper.eq(Blog::getIsPublish,"1");//发布
            blogLambdaQueryWrapper.in(Blog::getUid,blogs);
            List<Blog> allBlogList = blogService.list(blogLambdaQueryWrapper);
            blogMap = allBlogList.stream().collect(Collectors.toMap(Blog::getUid, Function.identity()));
        }

        if (CollectionUtils.isNotEmpty(records)) {
            notifyLogService.updateBatchById(records);
        }
        Map<Long, Comment> finalCommentMap = commentMap;
        Map<Long, Blog> finalBlogMap = blogMap;
        records.forEach(item -> {
            //设置用户信息
            if (StringUtils.isNotEmpty(item.getUserId())) {
                item.setFromUser(userMap.get(item.getUserId()));
            }
            //恢复的评论
            if (ObjectUtil.isNotEmpty(item.getProdId()) && finalCommentMap !=null) {
                if(ObjectUtil.isNull(finalCommentMap.get(item.getProdId()))){
                    item.setIsShow(false);
                    item.setContent("已下架");
                }else {
                    item.setIsShow(true);
                    item.setContent(finalCommentMap.get(item.getProdId()).getContent());
                }
            }
            //评论的圈子
            else if(ObjectUtil.isNotEmpty(item.getBlogId()) && finalBlogMap !=null){
                // 表示 为分享动态 卡片形式展示
                if(ObjectUtil.isNotEmpty(finalBlogMap.get(Long.valueOf(item.getBlogId()))) && finalBlogMap.get(Long.valueOf(item.getBlogId())).getType() == 4){
                    item.setRemindType(4);
                }
                if(ObjectUtil.isNull(finalBlogMap.get(Long.valueOf(item.getBlogId())))){
                    item.setIsShow(false);
                    item.setContent("已下架");
                }else if(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource()==1){
                    item.setIsShow(true);
                    item.setArticleSource(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource());//是否跳转详情
                    item.setContent(finalBlogMap.get(Long.valueOf(item.getBlogId())).getContent());
                }else {
                    item.setIsShow(true);
                    item.setArticleSource(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource());//是否跳转详情
                    item.setContent(finalBlogMap.get(Long.valueOf(item.getBlogId())).getTitle());
                }
            }else{
                item.setIsShow(true);
            }

        });
        notifyReminds.setRecords(records);
        return ServerResponseEntity.success(notifyReminds);
    }

    @GetMapping("/getSupportList")
    @Operation(summary =  "查询点赞消息列表", description = "查询点赞消息列表")
    public ServerResponseEntity<IPage<NotifyLog>> getSupportList(PageParam<NotifyLog> page) {
        String userId = SecurityUtils.getUser().getUserId();
        LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, userId);
        List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
        IPage<NotifyLog> notifyReminds = notifyLogService.page(page,
                new LambdaQueryWrapper<NotifyLog>()
                        .eq(NotifyLog::getRemindId, userId)
                        .ne(NotifyLog::getStatus, -1)
                        .eq(NotifyLog::getType,2)
                        .eq(NotifyLog::getRemindType, 3)
                        .notIn(CollUtil.isNotEmpty(blockUserIds), NotifyLog::getUserId, blockUserIds)
                        .orderByDesc(NotifyLog::getCreateTime));
        List<NotifyLog> records = notifyReminds.getRecords();
        List<String> userIds = new ArrayList<>();
        List<Long> blogs = new ArrayList<>();
        List<Long> comments = new ArrayList<>();
        records.forEach(record -> {
            record.setStatus(1);
            userIds.add(record.getUserId());
            if(record.getProdId()!=null){
                comments.add(record.getProdId());
            }else{
                blogs.add(Long.valueOf(record.getBlogId()));
            }
        });
        // 获取用户列表
        Collection<User> userList = new ArrayList<>();
        Map<String, String> remarkMap = new HashMap<>();
        if (userIds.size() > 0) {
            userList = userService.listByIds(userIds);
            List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, userIds));
            remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        }
        // 过滤掉用户的敏感信息
        List<User> filterUserList = new ArrayList<>();
        Map<String, String> finalRemarkMap = remarkMap;
        userList.forEach(item -> {
            User user = new User();
            user.setPic(item.getPic());
            user.setUserId(item.getUserId());
            String name = item.getNickName();
            if (StringUtils.isNotEmpty(finalRemarkMap.get(item.getUserId()))) {
                name = finalRemarkMap.get(item.getUserId());
            }
            user.setIsHasRealName(StrUtil.isNotEmpty(item.getIdNumber()));
            user.setNickName(name);
            filterUserList.add(user);
        });
        if(userIds.contains("admin")){
            User user = new User();
//            user.setPic(item.getPic());
            user.setUserId("admin");
            user.setNickName("平台");
            filterUserList.add(user);
        }
        List<User> filterUserListTo = filterUserList.stream().distinct().collect(Collectors.toList());
        Map<String, User> userMap = filterUserListTo.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
        Map<Long, Comment> commentMap = null;
        //获取评论或者博客内容
        if(comments.size()>0){
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            wrapper.in("uid",comments);
            //分页
            wrapper.eq("status", 1);
            // 查询出该文章下所有的子评论
            List<Comment> allCommentList = commentService.list(wrapper);
            commentMap = allCommentList.stream().collect(Collectors.toMap(Comment::getUid, Function.identity()));
        }
        Map<Long, Blog> blogMap= null;
        if(blogs.size()>0){
            LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            blogLambdaQueryWrapper.eq(Blog::getStatus,1);//审核通过
            blogLambdaQueryWrapper.eq(Blog::getIsPublish,"1");//发布
            blogLambdaQueryWrapper.in(Blog::getUid,blogs);
            List<Blog> allBlogList = blogService.list(blogLambdaQueryWrapper);
            blogMap = allBlogList.stream().collect(Collectors.toMap(Blog::getUid, Function.identity()));
        }

        if (CollectionUtils.isNotEmpty(records)) {
            notifyLogService.updateBatchById(records);
        }

        Map<Long, Comment> finalCommentMap = commentMap;
        Map<Long, Blog> finalBlogMap = blogMap;
        records.forEach(item -> {
            //设置用户信息
            if (StringUtils.isNotEmpty(item.getUserId())) {
                item.setFromUser(userMap.get(item.getUserId()));
            }
            //评论的评论
            if (ObjectUtil.isNotEmpty(item.getProdId()) && finalCommentMap !=null) {
                if(ObjectUtil.isNull(finalCommentMap.get(item.getProdId()))){
                    item.setIsShow(false);
                    item.setContent("已下架");
                }else {
                    item.setIsShow(true);
                    item.setContent(finalCommentMap.get(item.getProdId()).getContent());
                }
            }
            //评论的博客
            else if(ObjectUtil.isNotEmpty(item.getBlogId()) && finalBlogMap !=null){
                // 表示 为分享动态 卡片形式展示
                if(ObjectUtil.isNotEmpty(finalBlogMap.get(Long.valueOf(item.getBlogId()))) && finalBlogMap.get(Long.valueOf(item.getBlogId())).getType() == 4){
                    item.setRemindType(4);
                }
                if(ObjectUtil.isNull(finalBlogMap.get(Long.valueOf(item.getBlogId())))){
                    item.setIsShow(false);
                    item.setContent("已下架");
                }else if(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource()==1){
                    item.setIsShow(true);
                    item.setArticleSource(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource());//是否跳转详情
                    item.setContent(finalBlogMap.get(Long.valueOf(item.getBlogId())).getContent());
                }else {
                    item.setIsShow(true);
                    item.setArticleSource(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource());//是否跳转详情
                    item.setContent(finalBlogMap.get(Long.valueOf(item.getBlogId())).getTitle());
                }
            }else{
                item.setIsShow(true);
            }
        });
        notifyReminds.setRecords(records);
        return ServerResponseEntity.success(notifyReminds);
    }

    @GetMapping("/getCollentList")
    @Operation(summary =  "查询收藏消息列表", description = "查询点赞收藏消息列表")
    public ServerResponseEntity<IPage<NotifyLog>> getCollentList(PageParam<NotifyLog> page) {
        String userId = SecurityUtils.getUser().getUserId();
        LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, userId);
        List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
        IPage<NotifyLog> notifyReminds = notifyLogService.page(page,
                new LambdaQueryWrapper<NotifyLog>()
                        .eq(NotifyLog::getRemindId, userId)
                        .ne(NotifyLog::getStatus, -1)
                        .eq(NotifyLog::getType,3)
                        .eq(NotifyLog::getRemindType, 3)
                        .notIn(CollUtil.isNotEmpty(blockUserIds), NotifyLog::getUserId, blockUserIds)
                        .orderByDesc(NotifyLog::getCreateTime));
        List<NotifyLog> records = notifyReminds.getRecords();
        List<String> userIds = new ArrayList<>();
        List<Long> blogs = new ArrayList<>();//动态
        records.forEach(record -> {
            record.setStatus(1);
            userIds.add(record.getUserId());
            if(record.getProdId()!=null){
               // comments.add(record.getProdId()); 商品和展厅DOTO
            }else{
                blogs.add(Long.valueOf(record.getBlogId()));
            }
        });
        // 获取用户列表
        Collection<User> userList = new ArrayList<>();
        Map<String, String> remarkMap = new HashMap<>();
        if (userIds.size() > 0) {
            userList = userService.listByIds(userIds);
            List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, userIds));
            remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        }
        // 过滤掉用户的敏感信息
        List<User> filterUserList = new ArrayList<>();
        Map<String, String> finalRemarkMap = remarkMap;
        userList.forEach(item -> {
            User user = new User();
            user.setPic(item.getPic());
            user.setUserId(item.getUserId());
            String name = item.getNickName();
            if (StringUtils.isNotEmpty(finalRemarkMap.get(item.getUserId()))) {
                name = finalRemarkMap.get(item.getUserId());
            }
            user.setIsHasRealName(StrUtil.isNotEmpty(item.getIdNumber()));
            user.setNickName(name);
            filterUserList.add(user);
        });
        if(userIds.contains("admin")){
            User user = new User();
//            user.setPic(item.getPic());
            user.setUserId("admin");
            user.setNickName("平台");
            filterUserList.add(user);
        }
        List<User> filterUserListTo = filterUserList.stream().distinct().collect(Collectors.toList());
        Map<String, User> userMap = filterUserListTo.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));

        Map<Long, Blog> blogMap= null;
        if(blogs.size()>0){
            LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            blogLambdaQueryWrapper.eq(Blog::getStatus,1);//审核通过
            blogLambdaQueryWrapper.eq(Blog::getIsPublish,"1");//发布
            blogLambdaQueryWrapper.in(Blog::getUid,blogs);
            List<Blog> allBlogList = blogService.list(blogLambdaQueryWrapper);
            blogMap = allBlogList.stream().collect(Collectors.toMap(Blog::getUid, Function.identity()));
        }
        if (CollectionUtils.isNotEmpty(records)) {
            notifyLogService.updateBatchById(records);
        }

        Map<Long, Blog> finalBlogMap = blogMap;
        records.forEach(item -> {
            //设置用户信息
            if (StringUtils.isNotEmpty(item.getUserId())) {
                item.setFromUser(userMap.get(item.getUserId()));
            }
            //收藏的动态
            if(ObjectUtil.isNotEmpty(item.getBlogId()) && finalBlogMap !=null){
                // 表示 为分享动态 卡片形式展示
                if(ObjectUtil.isNotEmpty(finalBlogMap.get(Long.valueOf(item.getBlogId()))) && finalBlogMap.get(Long.valueOf(item.getBlogId())).getType() == 4){
                    item.setRemindType(4);
                }
                if(ObjectUtil.isNull(finalBlogMap.get(Long.valueOf(item.getBlogId())))){
                    item.setIsShow(false);
                    item.setContent("已下架");
                }else if(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource()==1){
                    item.setIsShow(true);//是否跳转详情
                    item.setArticleSource(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource());//是否跳转详情
                    item.setContent(finalBlogMap.get(Long.valueOf(item.getBlogId())).getContent());
                }else {
                    item.setIsShow(true);
                    item.setArticleSource(finalBlogMap.get(Long.valueOf(item.getBlogId())).getArticleSource());
                    item.setContent(finalBlogMap.get(Long.valueOf(item.getBlogId())).getTitle());
                }
            }else{
                item.setIsShow(true);
            }
        });
        notifyReminds.setRecords(records);
        return ServerResponseEntity.success(notifyReminds);
    }

    @GetMapping("/getUnCollentAndSupportListCount")
    @Operation(summary =  "查询收藏点赞消息列表", description = "查询点赞收藏消息列表")
    public ServerResponseEntity<Long> getUnCollentAndSupportListCount() {
        String userId = SecurityUtils.getUser().getUserId();
        long count = notifyLogService.count(
                new LambdaQueryWrapper<NotifyLog>()
                        .eq(NotifyLog::getRemindId, userId)
                        .eq(NotifyLog::getStatus, 0)
                        .in(NotifyLog::getType,3,2)
                        .eq(NotifyLog::getRemindType, 3));
        return ServerResponseEntity.success(count);
    }



    @GetMapping("/getUnAllCount")
    @Operation(summary =  "消息主页所有未读数量", description = "消息主页所有未读数量")
    public ServerResponseEntity<Map<String,Long>> getUnAllCount() {
        String userId = SecurityUtils.getUser().getUserId();
        Map<String,Long> res = new HashMap<>();
        LambdaQueryWrapper<UserBlock> eq = Wrappers.lambdaQuery(UserBlock.class).select(UserBlock::getBlockUserId).eq(UserBlock::getUserId, userId);
        List<String> blockUserIds = userBlockService.listObjs(eq, ub -> ub.toString());
        List<NotifyLog> lsit =  notifyLogService.list(
                new LambdaQueryWrapper<NotifyLog>()
                        .eq(NotifyLog::getRemindId, userId)
                        .eq(NotifyLog::getStatus, 0)
                        .eq(NotifyLog::getRemindType, 3).notIn(CollUtil.isNotEmpty(blockUserIds), NotifyLog::getUserId, blockUserIds));

        long count1 = lsit.stream().filter(notifyLog -> notifyLog.getType() != null && (notifyLog.getType() == 2 || notifyLog.getType() == 3)).count(); //点赞收藏
        long count2 = lsit.stream().filter(notifyLog -> notifyLog.getType() != null && notifyLog.getType() == 4).count(); //关注
        long count3 = lsit.stream().filter(notifyLog -> notifyLog.getType() != null && notifyLog.getType() == 1).count(); //评论
        long count4 = lsit.stream().filter(notifyLog -> notifyLog.getSendType() <=50).count(); //系统消息

        res.put("unCollentAndSupportListCount",count1);
        res.put("unFollowListCount",count2);
        res.put("unCommentListCount",count3);
        res.put("unReadCount",count4);
        res.put("unAllCount",count4+count2+count3+count4);
        return ServerResponseEntity.success(res);
    }
}
